package com.demo.myvideoplayer;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends Activity {
    public static String ip = "";
    public static String token = "";
    EditText et_ip;
    EditText et_id;
    EditText et_pwd;
    Button btn_login;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        et_ip = findViewById(R.id.et_ip);
        et_id = findViewById(R.id.et_id);
        et_pwd = findViewById(R.id.et_pwd);
        btn_login = findViewById(R.id.btn_login);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(et_ip.getText().toString().isEmpty()){
                    Toast.makeText(LoginActivity.this, "请输入ip地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(et_id.getText().toString().isEmpty()){
                    Toast.makeText(LoginActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(et_pwd.getText().toString().isEmpty()){
                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                login();
            }
        });
    }

    private void login(){
        String url = et_ip.getText().toString()+"/user/login";
        //1.拿到okHttpClient对象,可以设置连接超时等
        OkHttpClient okHttpClient=new OkHttpClient();
        Map<String,Object> headersMap = new HashMap<>();
        headersMap.put("Content-Type","application/json");
        Map<String ,Object> bodyMap = new HashMap<>();
        bodyMap.put("username", et_id.getText().toString());
        bodyMap.put("password", et_pwd.getText().toString());
        ;
        //构建请求体
        RequestBody requestBody = RequestBody.create(null, new JSONObject(bodyMap).toString());
        //构建请求头
        Headers.Builder headerBuilder = new Headers.Builder();
        headersMap.forEach((key,value)-> headerBuilder.add(key,value.toString()));
        Headers headers = headerBuilder.build();

        //创建请求
        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(requestBody)
                .build();

        //3.将Request封装为Call
        Call call = okHttpClient.newCall(request);
        //4.执行call
        //方法一Response response=call.execute();//汇抛出IO异常，同步方法
        //方法二,异步方法，放到队列中,处于子线程中，无法更新UI
        call.enqueue(new Callback() {
            //请求时失败时调用
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(LoginActivity.this, "请输入正确ip地址", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            //请求成功时调用
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ip = et_ip.getText().toString();
                //处于子线程中，能够进行大文件下载，但是无法更新UI
                final String res = response.body().string();//请求成功时返回的东西

                try {
                    JSONObject jsonObject = new JSONObject(res);
                    //runOnUiThread方法切换到主线程中，或者用handler机制也可以
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 更新ui
                            try {
                                if(jsonObject.getBoolean("successful")) {
                                    token = jsonObject.getString("data");
                                    startActivity(new Intent(LoginActivity.this, FaceActivity.class));
                                }
                                Toast.makeText(LoginActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }
}
